/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pt.regcolm.servico;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import pt.regcolm.sqlcon.BDPathCon;

/**
 * REST Web Service
 *
 * @author Tiago
 */
@Path("registo")
public class RegistoResource {

    
    private final static BDPathCon myCon = BDPathCon.getBDPathCon();
    
    
    @Context
    private UriInfo context;

    /**
     * Creates a new instance of RegistoResource
     */
    public RegistoResource() {
    }

    /**
     * Retrieves representation of an instance of pt.regcolm.servico.RegistoResource
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    public String getJson() {
       
        try {
            String toSend = "";
            CallableStatement sStmt = myCon.getCon().prepareCall("SELECT * FROM medida");
            ResultSet rs = sStmt.executeQuery();
            
            while(rs.next()){
                toSend += "ID: "+rs.getInt("idMedida")+" VALOR: "+rs.getDouble("medida")+" DATA: "+rs.getTimestamp("addedDate")+"\n";
            }
            
            return toSend;
        } catch (SQLException ex) {
            Logger.getLogger(RegistoResource.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    /**
     * PUT method for updating or creating an instance of RegistoResource
     * @param value
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
    @POST
    @Consumes("application/json")
    @Produces("text/plain")
    public String  putJson(@QueryParam("value") double value, String content) {
        
        try {
            Statement st = (Statement) myCon.getCon().createStatement();
            //PreparedStatement sStmt = myCon.getCon().prepareStatement("INSERT INTO medidas(medida) VALUES('"+value+"')");
            st.executeUpdate("INSERT INTO medida(medida) VALUES('"+value+"')");
            return "OK";
        } catch (SQLException ex) {
            Logger.getLogger(RegistoResource.class.getName()).log(Level.SEVERE, null, ex);
            return "FAIL";
        }
    }
}
